import 'package:api/pages/network/Dio/get/post_model.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

void main() => runApp(RootApp());

// 定义根目录Wigdget
class RootApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 根视图
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String result = "";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Dio网络请求 GET")),
      body: Row(
        children: [
          Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                FlatButton(
                  onPressed: () {
                    // TODO
                    getRequest();
                  },
                  child: Text("发起网络请求"),
                ),
                Text("文章标题 ${post != null ? post.title : ''}"),
                Text("文章详情 ${post != null ? post.body : ''}"),
              ],
            ),
          ),
        ],
      ),
    );
  }

  PostModel post;
  void getRequest() async {
    Dio dio = new Dio();
    // 请求地址
    // String url = "http://jsonplaceholder.typicode.com/users";
    String url = "http://jsonplaceholder.typicode.com/posts/1";
    // 发起get请求
    Response response = await dio.get(url);
    // 相应数据
    var data = response.data;
    PostModel res = PostModel.fromJson(data);

    setState(() {
      // result = data.toString();
      post = res;
    });
  }
}
